<template>
  <div class="space-list-container">
    <a-card title="我的空间" :bordered="false">
      <!-- 顶部操作区域 -->
      <div class="header-actions">
        <a-space>
          <a-button type="primary" @click="handleCreateSpace">
            <template #icon><PlusOutlined /></template>
            创建空间
          </a-button>
          <a-button @click="fetchSpaceList">
            <template #icon><ReloadOutlined /></template>
            刷新
          </a-button>
        </a-space>
      </div>

      <!-- 空间卡片列表 -->
      <div class="space-cards">
        <a-spin :spinning="loading">
          <a-row :gutter="[24, 24]" v-if="spaceList.length > 0">
            <!-- 公共空间卡片 -->
            <a-col :xs="24" :sm="12" :md="8" :lg="6">
              <a-card class="space-card public-space-card" hoverable @click="handleViewPublicSpace">
                <div class="space-card-content">
                  <div class="space-icon public-space-icon">
                    <GlobalOutlined />
                  </div>
                  <div class="space-info">
                    <h3 class="space-name">公共空间</h3>
                    <p class="space-description">查看所有公共图片</p>
                  </div>
                </div>
                <div class="space-stats">
                  <a-tag color="green">公共图片</a-tag>
                </div>
              </a-card>
            </a-col>

            <!-- 用户空间卡片 -->
            <a-col :xs="24" :sm="12" :md="8" :lg="6" v-for="space in spaceList" :key="space.id">
              <a-card class="space-card" hoverable @click="handleViewSpace(space)">
                <template #actions>
                  <EditOutlined @click.stop="handleEditSpace(space)" />
                  <TeamOutlined
                    v-if="space.spaceType === 1"
                    @click.stop="handleManageMembers(space)"
                    title="成员管理"
                  />
                  <a-popconfirm
                    title="确定要删除这个空间吗？"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="handleDeleteSpace(space)"
                  >
                    <DeleteOutlined @click.stop />
                  </a-popconfirm>
                </template>

                <div class="space-card-content">
                  <div class="space-icon">
                    <component
                      :is="space.spaceType === 0 ? UserOutlined : TeamOutlined"
                      :style="{ color: getSpaceTypeColor(space.spaceType) }"
                    />
                  </div>
                  <div class="space-info">
                    <h3 class="space-name">{{ space.spaceName }}</h3>
                    <p class="space-description">{{ getSpaceTypeText(space.spaceType) }}</p>
                  </div>
                </div>

                <div class="space-stats">
                  <a-tag :color="getSpaceLevelColor(space.spaceLevel)">
                    {{ getSpaceLevelText(space.spaceLevel) }}
                  </a-tag>
                  <div class="usage-info">
                    <div class="usage-item">
                      <span class="usage-label">存储:</span>
                      <span class="usage-value">
                        {{ formatFileSize(space.totalSize) }} / {{ formatFileSize(space.maxSize) }}
                      </span>
                    </div>
                    <a-progress
                      :percent="calculateUsageRate(space.totalSize, space.maxSize)"
                      size="small"
                      :stroke-color="getUsageColor(space.totalSize, space.maxSize)"
                    />
                    <div class="usage-item">
                      <span class="usage-label">图片:</span>
                      <span class="usage-value">{{ space.totalCount }} / {{ space.maxCount }}</span>
                    </div>
                    <a-progress
                      :percent="calculateUsageRate(space.totalCount, space.maxCount)"
                      size="small"
                      :stroke-color="getUsageColor(space.totalCount, space.maxCount)"
                    />
                  </div>
                </div>
              </a-card>
            </a-col>
          </a-row>

          <!-- 空状态 -->
          <a-empty v-else description="暂无空间，点击创建空间开始使用" />
        </a-spin>
      </div>
    </a-card>

    <!-- 创建空间弹窗 -->
    <a-modal
      v-model:open="createModalVisible"
      title="创建空间"
      @ok="handleConfirmCreate"
      @cancel="handleCancelCreate"
      :confirm-loading="createLoading"
    >
      <a-form ref="createFormRef" :model="createForm" :rules="createRules" layout="vertical">
        <a-form-item label="空间名称" name="spaceName">
          <a-input v-model:value="createForm.spaceName" placeholder="请输入空间名称" />
        </a-form-item>
        <a-form-item label="空间级别" name="spaceLevel">
          <a-select v-model:value="createForm.spaceLevel" placeholder="请选择空间级别">
            <a-select-option
              v-for="option in SPACE_LEVEL_OPTIONS"
              :key="option.value"
              :value="option.value"
            >
              <div class="level-option">
                <span>{{ option.label }}</span>
                <div class="level-info" v-if="spaceLevels && spaceLevels.length > 0">
                  <small>
                    存储:
                    {{ formatFileSize(parseInt(getSpaceLevelInfo(option.value)?.maxSize || '0')) }}
                    | 图片: {{ getSpaceLevelInfo(option.value)?.maxCount || 0 }}张
                  </small>
                </div>
              </div>
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="空间类型" name="spaceType">
          <a-radio-group v-model:value="createForm.spaceType">
            <a-radio :value="0">
              <UserOutlined /> 个人空间
              <div class="type-description">仅自己可见和管理</div>
            </a-radio>
            <a-radio :value="1">
              <TeamOutlined /> 团队空间
              <div class="type-description">可邀请团队成员协作</div>
            </a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 编辑空间弹窗 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑空间"
      @ok="handleConfirmEdit"
      @cancel="handleCancelEdit"
      :confirm-loading="editLoading"
    >
      <a-form ref="editFormRef" :model="editForm" :rules="editRules" layout="vertical">
        <a-form-item label="空间名称" name="spaceName">
          <a-input v-model:value="editForm.spaceName" placeholder="请输入空间名称" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  PlusOutlined,
  ReloadOutlined,
  EditOutlined,
  DeleteOutlined,
  UserOutlined,
  TeamOutlined,
  GlobalOutlined,
} from '@ant-design/icons-vue'
import { listSpaceVOByPage, addSpace, editSpace, deleteSpace, listSpaceLevel } from '@/api/space'
import type {
  SpaceVO,
  SpaceLevel,
  SpaceAddRequest,
  SpaceEditRequest,
  SpaceQueryRequest,
} from '@/types/space'
import {
  SPACE_LEVEL_OPTIONS,
  getSpaceLevelText,
  getSpaceLevelColor,
  getSpaceTypeText,
  getSpaceTypeColor,
  formatFileSize,
  calculateUsageRate,
} from '@/types/space'
import type { FormInstance } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const createLoading = ref(false)
const editLoading = ref(false)
const spaceList = ref<SpaceVO[]>([])
const spaceLevels = ref<SpaceLevel[]>([])
const createModalVisible = ref(false)
const editModalVisible = ref(false)
const createFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()

// 创建表单
const createForm = reactive<SpaceAddRequest>({
  spaceName: '',
  spaceLevel: 0,
  spaceType: 0,
})

// 编辑表单
const editForm = reactive<SpaceEditRequest>({
  id: '0',
  spaceName: '',
})

// 表单验证规则
const createRules = {
  spaceName: [
    { required: true, message: '请输入空间名称' },
    { max: 50, message: '空间名称不能超过50个字符' },
  ],
  spaceLevel: [{ required: true, message: '请选择空间级别' }],
  spaceType: [{ required: true, message: '请选择空间类型' }],
}

const editRules = {
  spaceName: [
    { required: true, message: '请输入空间名称' },
    { max: 50, message: '空间名称不能超过50个字符' },
  ],
}

// 获取空间列表 - 分页获取所有空间
const fetchSpaceList = async () => {
  try {
    loading.value = true
    const allSpaces: SpaceVO[] = []
    let current = 1
    const pageSize = 20 // 接口限制最大20
    let hasMore = true

    while (hasMore) {
      const params: SpaceQueryRequest = {
        current,
        pageSize,
        userId: userStore.loginUser?.id,
      }

      // 传userId参数，让后端根据当前登录用户筛选
      const response = await listSpaceVOByPage(params)

      // Handle different possible response structures
      const pageData = response.data.data || response.data
      if (!pageData || !pageData.records) {
        console.warn('Invalid response structure:', response.data)
        break
      }

      const { records, total } = pageData
      console.log('空间列表:', records)
      console.log('空间信息:', records[0])
      allSpaces.push(...records)

      // 检查是否还有更多数据
      hasMore = current * pageSize < total
      current++
    }

    // 过滤出当前用户的空间
    spaceList.value = allSpaces
    console.log('空间列表:', spaceList.value)
    console.log('空间信息:', spaceList.value[0])
  } catch (error: unknown) {
    console.error('获取空间列表失败:', error)
    // 如果后端空间接口尚未实现，不显示错误提示，设置为空数组
    spaceList.value = []
    // message.error('空间功能暂未开放，敬请期待')
  } finally {
    loading.value = false
  }
}

// 获取空间级别列表
const fetchSpaceLevels = async () => {
  try {
    const response = await listSpaceLevel()
    spaceLevels.value = response.data.data
    console.log('空间级别列表:', spaceLevels.value)
  } catch (error: unknown) {
    console.error('获取空间级别失败:', error)
    // 如果后端接口尚未实现，设置默认的空间级别
    spaceLevels.value = [
      { level: 0, name: '普通版', maxSize: '157286400', maxCount: '200' }, // ~150MB, 200张
      { level: 1, name: '专业版', maxSize: '1073741824', maxCount: '1500' }, // 1GB, 1500张
      { level: 2, name: '旗舰版', maxSize: '10737418240', maxCount: '20000' }, // 10GB, 20000张
    ]
    console.log('空间级别列表:', spaceLevels.value)
  }
}

// 获取空间级别信息
const getSpaceLevelInfo = (level: number) => {
  return spaceLevels.value.find((item) => item.level === level)
}

// 获取使用率颜色
const getUsageColor = (used: number, total: number) => {
  const rate = calculateUsageRate(used, total)
  if (rate >= 90) return '#ff4d4f'
  if (rate >= 70) return '#fa8c16'
  return '#52c41a'
}

// 查看公共空间
const handleViewPublicSpace = () => {
  router.push('/')
}

// 查看空间
const handleViewSpace = (space: SpaceVO) => {
  // 跳转到空间图片页面，传递空间ID和名称
  router.push({
    name: 'SpacePictures',
    params: { spaceId: space.id },
    query: { spaceName: space.spaceName },
  })
}

// 管理团队成员
const handleManageMembers = (space: SpaceVO) => {
  // 跳转到团队成员管理页面，传递空间ID和名称
  router.push({
    name: 'SpaceTeamMember',
    params: { spaceId: space.id },
    query: { spaceName: space.spaceName },
  })
}

// 创建空间
const handleCreateSpace = () => {
  console.log('创建空间按钮被点击')
  createForm.spaceName = ''
  createForm.spaceLevel = 0
  createForm.spaceType = 0
  createModalVisible.value = true
  console.log('创建弹窗应该显示:', createModalVisible.value)
}

// 确认创建
const handleConfirmCreate = () => {
  createFormRef.value
    ?.validateFields()
    .then(async () => {
      try {
        createLoading.value = true
        await addSpace(createForm)
        message.success('创建空间成功')
        createModalVisible.value = false
        fetchSpaceList()
      } catch (error: unknown) {
        console.error('创建空间失败:', error)
        message.error('创建空间失败')
      } finally {
        createLoading.value = false
      }
    })
    .catch(() => {
      // 验证失败，不做任何处理
    })
}

// 取消创建
const handleCancelCreate = () => {
  createModalVisible.value = false
  createFormRef.value?.resetFields()
}

// 编辑空间
const handleEditSpace = (space: SpaceVO) => {
  editForm.id = space.id
  editForm.spaceName = space.spaceName
  editModalVisible.value = true
}

// 确认编辑
const handleConfirmEdit = () => {
  editFormRef.value
    ?.validateFields()
    .then(async () => {
      try {
        editLoading.value = true
        await editSpace(editForm)
        message.success('编辑空间成功')
        editModalVisible.value = false
        fetchSpaceList()
      } catch (error: unknown) {
        console.error('编辑空间失败:', error)
        message.error('编辑空间失败')
      } finally {
        editLoading.value = false
      }
    })
    .catch(() => {
      // 验证失败，不做任何处理
    })
}

// 取消编辑
const handleCancelEdit = () => {
  editModalVisible.value = false
  editFormRef.value?.resetFields()
}

// 删除空间
const handleDeleteSpace = async (space: SpaceVO) => {
  try {
    await deleteSpace({ id: space.id })
    message.success('删除空间成功')
    fetchSpaceList()
  } catch (error: unknown) {
    console.error('删除空间失败:', error)
    message.error('删除空间失败')
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchSpaceList()
  fetchSpaceLevels()
})
</script>

<style scoped>
.space-list-container {
  padding: 24px;
}

.header-actions {
  margin-bottom: 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.space-cards {
  min-height: 400px;
}

.space-card {
  height: 100%;
  transition: all 0.3s;
}

.space-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.public-space-card {
  border: 2px solid #52c41a;
  background: linear-gradient(135deg, #f6ffed 0%, #f6ffed 100%);
}

.space-card-content {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
}

.space-icon {
  font-size: 24px;
  margin-right: 12px;
  color: #1890ff;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background: #f0f2f5;
  border-radius: 8px;
}

.public-space-icon {
  color: #52c41a;
  background: #f6ffed;
}

.space-info {
  flex: 1;
}

.space-name {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #262626;
}

.space-description {
  margin: 0;
  font-size: 12px;
  color: #8c8c8c;
}

.space-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.usage-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.usage-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.usage-label {
  color: #666;
}

.usage-value {
  color: #262626;
  font-weight: 500;
}

.level-option {
  display: flex;
  flex-direction: column;
}

.level-info {
  margin-top: 4px;
  color: #666;
}

.type-description {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

:deep(.ant-card-body) {
  padding: 20px;
}

:deep(.ant-card-actions) {
  background: #fafafa;
}

:deep(.ant-progress-line) {
  margin: 2px 0;
}

:deep(.ant-radio-wrapper) {
  display: flex;
  align-items: flex-start;
  margin-bottom: 16px;
  padding: 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  transition: all 0.3s;
}

:deep(.ant-radio-wrapper:hover) {
  border-color: #1890ff;
}

:deep(.ant-radio-wrapper-checked) {
  border-color: #1890ff;
  background: #f6ffed;
}

:deep(.ant-empty-description) {
  color: #999;
}
</style>
